<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ScoreRuleController;
use App\Models\ScoreInfo;
use App\Models\SignScore;
use App\Models\UserLibraryInfo;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 用户签到积分
 */
class SignScoreController extends Controller
{
    public $model;
    public $scoreInfoModel;
    public function __construct()
    {
        parent::__construct();
        $this->model = new SignScore();
        $this->scoreInfoModel = new ScoreInfo();
    }

    /**
     * 获取积分签到信息
     * @param token  用户token
     */
    public function signScoreInfo()
    {
        //不显示积分系统，直接返回错误
        if (config('other.is_need_score') !== true) {
            $data['count'] = 0;
            $data['normal_score'] = 0;
            $data['last_score'] = 0; //这里是额外增加
            $data['is_sign'] = 0;
            $data['share_score'] = 0;
            $data['share_times'] = 0;
            $data['invite_user'] = false; //是否显示邀请二维码按钮

            return $this->returnApi(200, '获取成功', true, $data);
        }
        //  $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        $last_date = date("Y-m-d", strtotime("-1 day"));
        $now_date = date("Y-m-d");
        $count = 0;
        $is_sign = 0;

        $now_day_sign = $this->model->where('account_id', $account_id)->where('date', $now_date)->first();
        if ($now_day_sign) {
            $is_sign = true;
            $count = $now_day_sign->count;
        } else {
            $last_day_sign = $this->model->where('account_id', $account_id)->where('date', $last_date)->first();
            if ($last_day_sign) {
                $count = $last_day_sign->count;
                if ($last_day_sign->count == 7) {
                    $count = 0;
                }
            }
        }

        $normal_score = $this->scoreInfoModel->where('type', 13)->where('is_open', 1)->where('is_del', 1)->first();
        $normal_score = $normal_score ? $normal_score['score'] : 0;
        $last_score = $this->scoreInfoModel->where('type', 14)->where('is_open', 1)->where('is_del', 1)->first();
        $last_score = $last_score ? $last_score['score'] : 0;
        $share = $this->scoreInfoModel->where('type', 2)->where('is_open', 1)->where('is_del', 1)->first();

        $data['count'] = $count;
        $data['normal_score'] = $normal_score;
        $data['last_score'] = $last_score + $normal_score; //这里是额外增加
        $data['is_sign'] = $is_sign;
        $data['share_score'] = $share ? $share->score : 0;
        $data['share_times'] = $share ? $share->number : 0;
        $data['invite_user'] = config('other.invite_user'); //是否显示邀请二维码按钮

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 用户打卡签到
     * @param token  用户token
     */
    public function sign()
    {
        //不执行积分操作
        if (config('other.is_need_score') !== true) {
            return $this->returnApi(202, "网络错误，请稍后重试!");
        }

        $is_score1 = $this->scoreInfoModel->where('type', 13)->where('is_open', 1)->where('is_del', 1)->first();
        $is_score1 = $is_score1 ? $is_score1['score'] : 0;
        $is_score2 = $this->scoreInfoModel->where('type', 14)->where('is_open', 1)->where('is_del', 1)->first();
        $is_score2 = $is_score2 ? $is_score2['score'] : 0;

        if (empty($is_score1) && empty($is_score2)) {
            return $this->returnApi(202, "网络错误，请稍后重试");
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];

        //判断读者证号密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }

        //限制用户点击太快
        $key = md5($user_id);
        $oldKey =  Cache::get($key); //没有缓存返回false
        if ($oldKey) {
            return $this->returnApi(201, "系统处理中，请稍后重试");
        } else {
            Cache::put($key, 1, 10);
        }

        $last_date = date("Y-m-d", strtotime("-1 day"));
        $now_date = date("Y-m-d");

        $now_day_sign = $this->model->where('account_id', $account_id)->where('date', $now_date)->first();

        if ($now_day_sign) {
            return $this->returnApi(202, '今天已签到');
        }

        $last_day_sign = $this->model->where('account_id', $account_id)->where('date', $last_date)->first();
        $count = 1;
        if ($last_day_sign) {
            if ($last_day_sign->count < 7) {
                $count = $last_day_sign->count + 1;
            }
        }

        $data = [
            'count' => $count,
            'date' => $now_date,
            'user_id' => $user_id,
            'account_id' => $account_id,
            'create_time' => date("Y-m-d H:i:s")
        ];

        DB::beginTransaction();
        try {
            $this->model->add($data);

            $score = $is_score1;

            $type_id = 13;
            $intro = '签到成功增加 ' . $score . ' 积分';
            if ($count == 7) {
                $score = $score +  $is_score2;
                $type_id = 14;
                $intro = '连续签到成功增加 ' . $score . ' 积分';
            }

            //用户积分操作  与 系统消息
            $system_id = $this->systemAdd("签到成功", $user_id, $account_id, 10, null, '签到成功: +' . $score . "积分");

            $scoreRuleObj = new \App\Http\Controllers\ScoreRuleController();
            $scoreRuleObj->addScoreLog([
                'user_id' => $user_id,
                'account_id' => $account_id,
                'system_id' => $system_id,
                'score' => $score,
                'total_score' => $score,
                'type_id' => $type_id,
                'type' => '签到成功',
                'intro' => $intro,
                'create_time' => date("Y-m-d H:i:s")
            ]);

            //增加用户积分
            // UserLibraryInfo::where('id' , $account_id)->increment('score' , $score);
            $scoreRuleObj = new ScoreRuleController();
            $scoreRuleObj->setUserScore($user_id, $account_id, $score); //添加积分消息

            DB::commit();
            return $this->returnApi(200, '签到成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '签到失败，请稍后再试');
        }
    }
}
